package com.jihu.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jihu.mall.common.constant.ProductConstant;
import com.jihu.mall.product.dao.AttrAttrgroupRelationDao;
import com.jihu.mall.product.dao.AttrGroupDao;
import com.jihu.mall.product.dao.CategoryDao;
import com.jihu.mall.product.entity.AttrAttrgroupRelationEntity;
import com.jihu.mall.product.entity.AttrGroupEntity;
import com.jihu.mall.product.entity.CategoryEntity;
import com.jihu.mall.product.service.CategoryService;
import com.jihu.mall.product.vo.AttrGroupRelationVo;
import com.jihu.mall.product.vo.AttrResVo;
import com.jihu.mall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jihu.mall.common.utils.PageUtils;
import com.jihu.mall.common.utils.Query;

import com.jihu.mall.product.dao.AttrDao;
import com.jihu.mall.product.entity.AttrEntity;
import com.jihu.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    @Transactional
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        //保存基本数据
        this.save(attrEntity);

        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null){
            //保存关联关系
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }

    }

    @Override
    @Transactional
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId,String attrType) {
        LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<AttrEntity>();
        wrapper.eq(AttrEntity::getAttrType,"base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if(catelogId != 0){
            wrapper.eq(AttrEntity::getCatelogId,catelogId);
        }
        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and((obj) ->{
               obj.eq(AttrEntity::getAttrId,key).or()
                       .like(AttrEntity::getAttrName,key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrResVo> attrResVos = records.stream().map(attrEntity -> {
            AttrResVo attrResVo = new AttrResVo();
            BeanUtils.copyProperties(attrEntity,attrResVo);

            //设置分类和分组的名字
            if("base".equalsIgnoreCase(attrType)){
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                        new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq(AttrAttrgroupRelationEntity::getAttrId,attrResVo.getAttrId()));
                if(Optional.ofNullable(attrAttrgroupRelationEntity).isPresent() && attrAttrgroupRelationEntity.getAttrGroupId() != null){
                    AttrGroupEntity attrGroup = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                    attrResVo.setGroupName(attrGroup.getAttrGroupName());
                }
            }

            CategoryEntity categoryEntity = categoryDao.selectById(attrResVo.getCatelogId());
            if(Optional.ofNullable(categoryEntity).isPresent()){
                attrResVo.setCatelogName(categoryEntity.getName());
            }
            return attrResVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrResVos);
        return pageUtils;
    }

    @Override
    @Cacheable(value = "attr",key = "'attrInfo:'+#{root.args[0]}")
    public AttrResVo getAttrInfo(Long attrId) {
        AttrEntity byId = this.getById(attrId);
        AttrResVo attrResVo = new AttrResVo();
        BeanUtils.copyProperties(byId,attrResVo);

        if(byId.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //设置分组信息
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq(AttrAttrgroupRelationEntity::getAttrId,attrResVo.getAttrId()));
            if(Optional.ofNullable(attrAttrgroupRelationEntity).isPresent()){
                attrResVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                if(Optional.ofNullable(attrGroupEntity).isPresent()){
                    attrResVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //设置分类信息
        List<Long> catelogPath = categoryService.findCatelogPath(attrResVo.getCatelogId());
        if(!CollectionUtils.isEmpty(catelogPath)){
            attrResVo.setCatelogPath(catelogPath);
            CategoryEntity categoryEntity = categoryDao.selectById(attrResVo.getCatelogId());
            attrResVo.setCatelogName(categoryEntity.getName());
        }
        return attrResVo;
    }

    @Override
    @Transactional
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
        attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());

        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            Integer count = attrAttrgroupRelationDao.selectCount(new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId,attr.getAttrId()));
            if(count > 0){
                //1.修改分组关联
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity,new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId,attr.getAttrId()));
            }else{
                //2.新增分组关联
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }

    }

    /**
     * 根据分组id查找关联的所有基本属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRaletionAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrgroupId));
        if(!CollectionUtils.isEmpty(attrAttrgroupRelationEntities)){
            List<Long> collect = attrAttrgroupRelationEntities.stream().map(entity -> {
                return entity.getAttrId();
            }).collect(Collectors.toList());
            Collection<AttrEntity> attrEntities = this.listByIds(collect);
            return (List<AttrEntity>) attrEntities;
        }
        return null;
    }

    @Override
    public void deleteRelation(List<AttrGroupRelationVo> vos) {
        //批量删除
        List<AttrAttrgroupRelationEntity> entities = vos.stream().map((item) -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelation(entities);

    }

    /**
     * 获取当前分组没有关联的所有属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getRaletionNoAttr(Map<String, Object> params, Long attrgroupId) {
        //1.当前分组只能只能关联自己所属分类里面的所有属性
        AttrGroupEntity attrGroup = attrGroupDao.selectById(attrgroupId);
        if(Optional.ofNullable(attrGroup).isPresent()){
            Long catelogId = attrGroup.getCatelogId();
            //2.当前分组只能关联别的分组没有引用的属性
            //2.1找到当前分类下的其他分组
            List<AttrGroupEntity> attrGroupEntities =
                    attrGroupDao.selectList(
                            new LambdaQueryWrapper<AttrGroupEntity>()
                                    .eq(AttrGroupEntity::getCatelogId, catelogId));
            List<Long> groupIds = attrGroupEntities.stream().map((item -> {
                return item.getAttrGroupId();
            })).collect(Collectors.toList());
            //2.2这些分组关联的属性
            List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                    .in(AttrAttrgroupRelationEntity::getAttrGroupId, groupIds));
            List<Long> attrIds = entities.stream().map(item -> {
                return item.getAttrId();
            }).collect(Collectors.toList());
            //2.3从当前分类的所有属性中移除这些属性

            String key = (String) params.get("key");
            LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<AttrEntity>().eq(AttrEntity::getCatelogId, catelogId);
            wrapper.eq(AttrEntity::getAttrType,ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
            if(!CollectionUtils.isEmpty(attrIds)){
                wrapper.notIn(AttrEntity::getAttrId,attrIds);
            }
            if(StringUtils.isNotEmpty(key)){
                wrapper.and(w ->{
                    w.eq(AttrEntity::getAttrId,key)
                     .or().like(AttrEntity::getAttrName,key);
                });
            }
            IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
            PageUtils pageUtils = new PageUtils(page);
            return pageUtils;
        }
        return null;
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {

        /**
         * SELECT attr_id FROM `pms_attr`
         * where attr_id in () and search_type = 1;
         */
        return baseMapper.selectSearchAttrIds(attrIds);
    }

}